package com.market.web;

import java.util.Locale;

import javax.faces.context.FacesContext;

import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.market.domain.User;

@Controller("viewController")
@Scope("session")
public class ViewController {

	private User.LANGUAGE language;
	
	private Boolean isShowAdminList = Boolean.TRUE;
	private Boolean isShowAdminDetail = Boolean.TRUE;
	
	

	public Boolean getIsShowAdminList() {
		return isShowAdminList;
	}

	public void setIsShowAdminList(Boolean isShowAdminList) {
		this.isShowAdminList = isShowAdminList;
	}

	public Boolean getIsShowAdminDetail() {
		return isShowAdminDetail;
	}

	public void setIsShowAdminDetail(Boolean isShowAdminDetail) {
		this.isShowAdminDetail = isShowAdminDetail;
	}

	public User.LANGUAGE getLanguage() {
		return this.language;
	}

	public void setLanguage(User.LANGUAGE language) {
		this.language = language;
		FacesContext.getCurrentInstance().getViewRoot()
				.setLocale(this.language.getLocale());
	}

	/**
	 * Every time show a new page to customer, this init method will be invoke
	 * to set the initial view of that page, put this method to masterTemplate
	 * <f:event listener="#{viewController.init}"
	 * type="preRenderComponent"></f:event>
	 */
	public void init() {
		Authentication au = SecurityContextHolder.getContext()
				.getAuthentication();
		if (au != null && au.getPrincipal() instanceof User) {
			User user = (User) au.getPrincipal();
			this.language = user.getLanguage();
			FacesContext.getCurrentInstance().getViewRoot()
					.setLocale(user.getLanguage().getLocale());

		} else {
			if (this.getLanguage() != null) {
				FacesContext.getCurrentInstance().getViewRoot()
						.setLocale(this.language.getLocale());
			} else {
				Locale locale = FacesContext.getCurrentInstance()
						.getExternalContext().getRequestLocale();
				if (locale.getLanguage().equalsIgnoreCase("zh")) {
					this.language = User.LANGUAGE.CHINESE;
				}else{
					if(locale.getLanguage().equalsIgnoreCase("fr")){
						this.language = User.LANGUAGE.FRENCH;
					}else{
						this.language=	User.LANGUAGE.ENGLISH;
					}
				}
				
				FacesContext.getCurrentInstance().getViewRoot()
						.setLocale(this.language.getLocale());
			}
		}
	}
}
